<template>
  <div id="EssayList">
    <!-- 查询 -->
    <div id="selectBar">
      <el-date-picker v-model="time" type="date" placeholder="请选择时间"></el-date-picker>
      <div id="authorityBar">
        <span id="authorityText">私有</span>
        <el-switch v-model="authority" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
      </div>
      <el-select v-model="moodId" placeholder="请选择心情">
        <el-option v-for="item in moodData" :key="item.id" :label="item.moodName" :value="item.id"></el-option>
      </el-select>
      <el-button icon="el-icon-search" class="search" circle @click="search(true)"></el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="essayData" border stripe class="el-table">
      <el-table-column prop="id" label="id" align="center"></el-table-column>
      <el-table-column label="随笔图片" align="center">
        <template slot-scope="scope">
          <el-image :src="GLOBAL.OSSImageUrlRoot + 'essayImage/' + scope.row.id + '.png'" fit="contain"
            style="height: 80px;" :preview-src-list="[GLOBAL.OSSImageUrlRoot + 'essayImage/' + scope.row.id + '.png']">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="随笔内容"></el-table-column>
      <el-table-column prop="time" label="时间" align="center"></el-table-column>
      <el-table-column label="权限" prop="authority" align="center">
        <template slot-scope="scope">
          {{ scope.row.authority == 0 ? '公开' : '私有' }}
        </template>
      </el-table-column>
      <el-table-column label="心情" align="center">
        <template slot-scope="scope">
          <el-image :src="GLOBAL.OSSImageUrlRoot + 'mood/' + scope.row.moodId + '.png'" fit="contain"
            :title="scope.row.moodId" style="height: 80px;"
            :preview-src-list="[GLOBAL.OSSImageUrlRoot + 'mood/' + scope.row.moodId + '.png']">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button
            @click="currentEditEssay = scope.row; currentEditEssay.authority = currentEditEssay.authority == 0 ? false : true; essayFormShow = true;"
            type="primary" icon="el-icon-edit" size="mini"></el-button>
          <el-button @click="currentEditEssay = scope.row; essayDeleteShow = true;" type="primary" icon="el-icon-delete"
            size="mini"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页按钮 -->
    <div id="paging">
      <el-pagination layout="prev, pager, next" :page-size="pageSize" :total="total" @current-change="pageCurrentChange">
      </el-pagination>
    </div>
    <!-- 删除随笔提示框 -->
    <el-dialog title="提示" :visible.sync="essayDeleteShow" width="30%">
      <span>确定删除该随笔么</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="essayDeleteShow = false">取 消</el-button>
        <el-button type="primary" @click="deleteEssay(); essayDeleteShow = false;">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑随笔提示框 -->
    <el-dialog title="编辑随笔" :visible.sync="essayFormShow">
      <el-form :model="currentEditEssay" label-position="top">
        <el-form-item>
          <span>id：{{ currentEditEssay.id }}</span>
        </el-form-item>
        <el-form-item label="随笔图片上传/修改">
          <el-image :src="GLOBAL.OSSImageUrlRoot + 'essayImage/' + currentEditEssay.id + '.png'" fit="contain"
            style="height: 80px;"
            :preview-src-list="[GLOBAL.OSSImageUrlRoot + 'essayImage/' + currentEditEssay.id + '.png']">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <el-upload class="upload-demo" :action="uploadUrl" :before-upload="beforeImgUpload" auto-upload
            :headers="imgUploadHeaders" :on-error="imgUploadError" :on-success="imgUploadSuccess" :limit="1"
            :on-exceed="handleExceed" accept=".jpg, .png" list-type="picture" :multiple="false" :file-list="fileList"
            name="file">
            <el-button size="small" type="primary">点击上传</el-button>
            <el-button size="small" type="danger" @click.stop="deleteEssayImage">删除图片</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，无需点击提交自动上传</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="currentEditEssay.content" id="el_input" type="textarea" autosize></el-input>
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker type="date" placeholder="选择日期" id="el_input" v-model="currentEditEssay.time"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <span id="authorityText">私有</span>
          <el-switch v-model="currentEditEssay.authority" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </el-form-item>
        <el-form-item label="心情">
          <el-image :src="GLOBAL.OSSImageUrlRoot + 'mood/' + currentEditEssay.moodId + '.png'" fit="contain"
            :title="currentEditEssay.moodId" style="height: 80px;"
            :preview-src-list="[GLOBAL.OSSImageUrlRoot + 'mood/' + currentEditEssay.moodId + '.png']">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <el-select v-model="currentEditEssay.moodId" placeholder="请选择心情" id="el_input">
            <el-option v-for="item in moodData" :key="item.id" :label="item.moodName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="essayFormShow = false">取 消</el-button>
        <el-button type="primary" @click="essayEdit(); essayFormShow = false">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      essayData: [],
      moodData: [],
      searchOrNot: false, // 是否搜索状态量，用于确定翻页后数据从那个方法得到
      currentPage: 1, // 当前页
      pageSize: 10, // 页大小
      total: 0, // 数据总数
      time: null, // 筛选时间
      authority: false, // 是否私有
      moodId: null, // 心情id
      essayFormShow: false, // 控制随笔编辑对话框显示/隐藏
      essayDeleteShow: false, // 控制随笔删除对话框显示/隐藏
      currentEditEssay: {}, // 当前编辑随笔的数据
      fileList: [], // 文件(图片)上传的文件list
      imgUploadHeaders: { 'Token': sessionStorage.getItem('token') }, // 请求头token信息，用于图片上传后端认证
    }
  },
  computed: {
    uploadUrl() { // 请求上传图片的url地址
      return this.$axios.defaults.baseURL + '/essay/login/uploadEssayImage/' + this.currentEditEssay.id
    },
  },
  methods: {
    // 默认，获取所有随笔数据
    getEssayData() {
      this.$axios({
        method: 'post',
        url: '/essay/login/getAllEssay/' + this.currentPage + '/' + this.pageSize
      }).then(res => {
        res.data.data.data.forEach(element => {
          element.time = element.time.slice(0, 10) // 格式化时间
        });
        this.essayData = res.data.data.data
        this.total = res.data.data.total
      })
    },
    // 获取所有的心情
    getAllMood() {
      this.$axios({
        method: 'post',
        url: '/mood/login/getAllMood'
      }).then(res => {
        this.moodData = res.data
      })
    },
    // 当element ui 的页数改变，同步页数
    pageCurrentChange(val) {
      this.currentPage = val // 更改当前页
      if (this.searchOrNot) { // 若搜索过，就用筛选搜索的方式查询数据
        this.search(false)
        return
      }
      this.getEssayData() // 默认，请求所有数据
    },
    // 筛选搜索获得数据,参数意思：表示是翻页查找(不需要重设页状态)，还是按钮点击查找(需要重设页状态)
    search(buttonSearchOrNot) {
      if (buttonSearchOrNot) { // 若为按钮点击搜索,重设页状态
        this.currentPage = 1
        this.total = 0
      }
      this.searchOrNot = true // 改变搜索状态量
      let data = new FormData()
      if (this.moodId != null) data.append("moodId", this.moodId)
      if (this.time != null) data.append("time", this.time)
      data.append("authority", this.authority ? 1 : 0)
      this.$axios({
        method: 'post',
        url: '/essay/login/selectSearch/' + this.currentPage + '/' + this.pageSize,
        data: data,
        headers: {
          'Content-Type': 'application/x-www-form-urlcoded'
        }
      }).then(res => {
        res.data.data.data.forEach(element => {
          element.time = element.time.slice(0, 10) // 格式化时间
        });
        this.essayData = res.data.data.data
        this.total = res.data.data.total
      })
    },
    // 删除随笔事件
    deleteEssay() {
      this.$axios({
        method: 'post',
        url: '/essay/login/deleteEssay/' + this.currentEditEssay.id
      }).then(res => {
        if (res.data) {
          this.$router.go(0) // 刷新页面
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
        } else {
          this.$message({
            showClose: true,
            message: '删除失败，出现错误了X.X',
            type: 'error'
          })
        }
      })
    },
    // 提交编辑随笔事件
    essayEdit() {
      if (this.currentEditEssay.content == '' || this.currentEditEssay.content == null || this.currentEditEssay.time == '' || this.currentEditEssay.time == null) {
        this.$message({
          message: '请完善信息再提交哦~',
          type: 'error',
          showClose: true
        })
        return
      }
      let data = new FormData()
      data.append("id", this.currentEditEssay.id)
      data.append("content", this.currentEditEssay.content)
      data.append("moodId", this.currentEditEssay.moodId)
      data.append("authority", this.currentEditEssay.authority ? 1 : 0)
      data.append("time", new Date(this.currentEditEssay.time))
      this.$axios({
        method: 'post',
        url: '/essay/login/updateEssay',
        data: data,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        }
      }).then(res => {
        if (res.data) {
          this.$router.go(0) // 刷新页面
          this.$message({
            showClose: true,
            message: '提交成功',
            type: 'success'
          })
        } else {
          this.$message({
            showClose: true,
            message: '提交失败，出现错误了X.X',
            type: 'error'
          })
        }
      })
    },
    // 处理图片上传多了的提示事件
    handleExceed() {
      this.$message({
        type: 'error',
        message: '限制只能上传一个文件哦',
        showClose: true,
      })
    },
    // 图片文件上传出现错误的提示事件
    imgUploadError() {
      this.$message({
        message: '文件上传出现错误X.X',
        type: 'error',
        showClose: true,
      })
    },
    // 图片文件上传成功的提示事件
    imgUploadSuccess() {
      this.$message({
        message: '上传成功',
        type: 'success',
        showClose: true
      })
    },
    // 图片文件上传前的文件类型检查
    beforeImgUpload(file) {
      if (this.getfileName(file.name) != '.jpg' && this.getfileName(file.name) != '.png') {
        this.$message({
          message: '上传封面图片文件格式只能为jpg或png',
          type: 'error',
          showClose: true,
        })
        return false
      }
    },
    deleteEssayImage() {
      this.$axios({
        method: 'post',
        url: '/essay/login/deleteEssayImage/' + this.currentEditEssay.id
      }).then(res => {
        if (res.data) {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
        } else {
          this.$message({
            showClose: true,
            message: '删除失败，出现错误了X.X',
            type: 'error'
          })
        }
      })
    },
    // 获取文件后缀工具函数
    getfileName(filename) {
      // 转换为小写
      const pos = filename.toLowerCase().lastIndexOf('.')
      let suffix = ''
      if (pos !== -1) {
        suffix = filename.substring(pos)
      }
      return suffix
    },

  },
  mounted() {
    this.getEssayData()
    this.getAllMood()
  }
}
</script>

<style lang="scss" scoped>
#selectBar {
  margin: 20px auto;
  display: flex;
  justify-content: center;
}

#authorityBar {
  margin: auto 20px;
}

#authorityText {
  margin-right: 10px;
}
</style>
<style scoped="scoped">
/* 筛选框 */
.el-date-editor.el-input,
.el-select {
  margin: auto 20px;
}

/deep/.el-input__inner {
  background-color: #202020;
}

/deep/#el_input {
  background-color: #fff;
}

.search {
  background-color: #202020;
  color: #fff;
}

/* 表格 */
.el-table {
  width: 80%;
  margin: 0 auto;
  border-radius: 20px;
}

.el-table__row {
  background-color: rgba(0, 0, 0, 0);
}

/deep/.el-table--border {
  border-color: #464646;
}

/deep/.el-table th.el-table__cell.is-leaf {
  border-color: #464646;
}

/deep/ .el-table thead tr>th {
  background-color: #202020 !important;
  color: #464646;
  border-color: #464646;
}

/deep/ .el-table tbody tr>td {
  background-color: #202020 !important;
  border-color: #464646;
}

/deep/.el-table::before,
/deep/.el-table__fixed-right::before {
  background-color: rgba(0, 0, 0, 0);
}

/deep/.el-table__empty-block {
  background-color: #202020;
}

.cell .el-button--primary {
  margin-bottom: 10px;
}

/deep/.el-table__body-wrapper {
  border-bottom: 1px solid;
}

/* 分页 */

/deep/.el-pagination {
  display: flex;
  justify-content: center;
  margin: 20px auto;
  color: #202020;
}

/deep/.el-pagination button {
  color: #fff;
  background-color: #202020;
}

/deep/ .el-pager li.active {
  color: rgb(255, 150, 50);
}

/deep/ .number {
  color: #fff;
}

/deep/ .number:hover {
  color: rgb(255, 150, 50);
}

/deep/.el-pager li {
  background-color: #202020;
}
</style>